// src/store/modules/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { doLogin } from "@/api/share/user"
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  () => {
    // 状态
    const userId = ref('')
    const username = ref('')
    const nickname = ref('')
    const email = ref('')
    const phone = ref('')
    const gender = ref('0')
    const avatar = ref(defAva)

    // 操作
    const login =  (loginData) => {
      const response =  doLogin(loginData)


      if (response.data) {
        setUserInfo(response.data)
      }
      return response
    }
    
    const setUserInfo = (userInfo) => {
      userId.value = userInfo.userId || ''
      username.value = userInfo.username || ''
      nickname.value = userInfo.nickname || ''
      email.value = userInfo.email || ''
      phone.value = userInfo.phone || ''
      gender.value = userInfo.gender || '0'
      avatar.value = userInfo.avatar || defAva
    }

    const clearUserInfo = () => {
      userId.value = ''
      username.value = ''
      nickname.value = ''
      email.value = ''
      phone.value = ''
      gender.value = '0'
      avatar.value = defAva
    }

    // 返回状态和操作
    return {
      userId,
      username,
      nickname,
      email,
      phone,
      gender,
      avatar,
      login,
      setUserInfo,
      clearUserInfo
    }
  },
  {
    // 持久化配置
    persist: {
      key: 'user-storage',
      storage: window.localStorage,
      paths: ['userId', 'username', 'nickname', 'email', 'phone', 'gender', 'avatar']
    }
  }
)

export default useUserStore